package java8stream;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * Created by ZhuQianli on 2018/1/17.
 */
public class ParallelSequential {
    public static void main(String[] args) {

        List<Long> list = new ArrayList<>(10000000);
        int sum = 0;
        for (long i = 0; i < 100; i++) {
            sum += i;
            list.add(i);
        }
        long ll = System.currentTimeMillis();
        Optional<Long> reduce2 = list.stream().reduce(Long::sum);
        System.out.println(System.currentTimeMillis() - ll);

        long l = System.currentTimeMillis();
        Optional<Long> reduce = list.stream().parallel().reduce(Long::sum);
        System.out.println(System.currentTimeMillis() - l);



        reduce.ifPresent(System.out::println);
        reduce2.ifPresent(System.out::println);


        // 测试结果  串行速度大于并行     应该是fork了太多线程 创建线程相对计算比较耗时
        long lll = System.currentTimeMillis();
        parallelSum(1000);
        System.out.println(System.currentTimeMillis() - lll);

        long llll = System.currentTimeMillis();
        sequentialSum(1000000000);
        System.out.println(System.currentTimeMillis() - llll);

    }

    public static long parallelSum(long n){
        return Stream.iterate(1L, i -> i +1).limit(n).parallel().reduce(0L,Long::sum);
    }
    public static long sequentialSum(long n){
        return Stream.iterate(1L, i -> i +1).limit(n).sequential().reduce(0L,Long::sum);
    }

}
